<template>

  <div
    style="padding: 10px; display: flex; align-items: flex-start; justify-content: space-between; flex-wrap: wrap; gap: 20px;">

    <!-- 步骤条 -->
    <div style="flex: 1; min-width: 300px;" v-if="!userStore.isMobile">
      <el-steps style="max-width: 80vw;" :space="600" :active="completeObj?.dictSort" finish-status="success">
        <el-step v-for="(item, index) in logs" :key="item.id" :title="item.operator" :description="item.completeDate" />
      </el-steps>
    </div>

    <div :style="userStore.isMobile ? 'width: 100%; margin-top: 10px;' : 'flex: 0 0 auto; margin-right: 80px;'">
      <div :style="userStore.isMobile ? 'display: flex; flex-direction: column; gap: 8px;' : 'display: inline;'">
        <div :style="userStore.isMobile ? 'display: flex; align-items: center;' : 'display: inline;'">
          应收金额：
          <el-tag size="large" type="primary" style="font-size: 14px; font-weight: bold; margin-left: 4px;">
            {{ amountInfo.should }}
          </el-tag>
        </div>
        <div :style="userStore.isMobile ? 'display: flex; align-items: center;' : 'display: inline;'">
          实收金额：
          <el-tag size="large" type="success" style="font-size: 14px; font-weight: bold; margin-left: 4px;">
            {{ amountInfo.actual }}
          </el-tag>
        </div>
        <div :style="userStore.isMobile ? 'display: flex; align-items: center;' : 'display: inline;'">
          管家婆应收金额：
          <el-tag size="large" type="warning" style="font-size: 14px; font-weight: bold; margin-left: 4px;">
            {{ amountInfo.gjpShould }}
          </el-tag>
        </div>
        <div :style="userStore.isMobile ? 'display: flex; align-items: center;' : 'display: inline;'">
          待收金额：
          <el-tag size="large" type="danger" style="font-size: 14px; font-weight: bold; margin-left: 4px;">
            {{ amountInfo.remaining }}
          </el-tag>
        </div>
      </div>
    </div>

  </div>


  <el-descriptions 
  class="margin-top" 
  title="" 
  :column="userStore.isMobile ? 1 : column" 
  :size="sizes" 
  border
  :direction="userStore.isMobile ? 'vertical' : 'horizontal'"
>
    <el-descriptions-item v-if="datas.companyNo">
      <template #label>
        <div class="cell-item" :style="userStore.isMobile ? mobileLabelStyle : ''">
          <el-icon :style="iconStyle">
            <Tickets />
          </el-icon>
          项目编号
        </div>
      </template>
      {{ datas.companyNo }}
    </el-descriptions-item>

    <el-descriptions-item v-if="datas.projectName">
      <template #label>
        <div class="cell-item" :style="userStore.isMobile ? mobileLabelStyle : ''">
          <el-icon :style="iconStyle">
            <Document />
          </el-icon>
          项目名称
        </div>
      </template>
      {{ datas.projectName }}
    </el-descriptions-item>

    <el-descriptions-item v-if="datas.createUserName">
      <template #label>
        <div class="cell-item" :style="userStore.isMobile ? mobileLabelStyle : ''">
          <el-icon :style="iconStyle">
            <user />
          </el-icon>
          发起人
        </div>
      </template>
      {{ datas.createUserName }}
    </el-descriptions-item>

    <el-descriptions-item v-if="datas.createTime">
      <template #label>
        <div class="cell-item" :style="userStore.isMobile ? mobileLabelStyle : ''">
          <el-icon :style="iconStyle">
            <user />
          </el-icon>
          发起时间
        </div>
      </template>
      {{ datas.createTime }}
    </el-descriptions-item>

    <el-descriptions-item v-if="datas.createDeptName">
      <template #label>
        <div class="cell-item" :style="userStore.isMobile ? mobileLabelStyle : ''">
          <el-icon :style="iconStyle">
            <HomeFilled />
          </el-icon>
          发起人所在部门
        </div>
      </template>
      {{ datas.createDeptName }}
    </el-descriptions-item>

    <el-descriptions-item v-if="datas.customerName">
      <template #label>
        <div class="cell-item" :style="userStore.isMobile ? mobileLabelStyle : ''">
          <el-icon :style="iconStyle">
            <UserFilled />
          </el-icon>
          客户名称
        </div>
      </template>
      {{ datas.customerName }}
    </el-descriptions-item>

    <el-descriptions-item v-if="datas.contractAmount">
      <template #label>
        <div class="cell-item" :style="userStore.isMobile ? mobileLabelStyle : ''">
          <el-icon :style="iconStyle">
            ￥
          </el-icon>
          合同金额
        </div>
      </template>
      {{ datas.contractAmount }}
    </el-descriptions-item>

    <el-descriptions-item v-if="datas.settlementAmount">
      <template #label>
        <div class="cell-item" :style="userStore.isMobile ? mobileLabelStyle : ''">
          <el-icon :style="iconStyle">
            ￥
          </el-icon>
          结算金额
        </div>
      </template>
      {{ datas.settlementAmount }}
    </el-descriptions-item>

    <el-descriptions-item v-if="datas.projectTypeName">
      <template #label>
        <div class="cell-item" :style="userStore.isMobile ? mobileLabelStyle : ''">
          <el-icon :style="iconStyle">
            <Histogram />
          </el-icon>
          项目类型
        </div>
      </template>
      <el-tag size="small">{{ datas.projectTypeName }}</el-tag>
    </el-descriptions-item>

    <el-descriptions-item v-if="datas.projectUnit">
      <template #label>
        <div class="cell-item" :style="userStore.isMobile ? mobileLabelStyle : ''">
          <el-icon :style="iconStyle">
            <OfficeBuilding />
          </el-icon>
          项目配合单位
        </div>
      </template>
      {{ datas.projectUnit }}
    </el-descriptions-item>

    <el-descriptions-item v-if="datas.planDate">
      <template #label>
        <div class="cell-item" :style="userStore.isMobile ? mobileLabelStyle : ''">
          <el-icon :style="iconStyle">
            <Calendar />
          </el-icon>
          合同签订日期
        </div>
      </template>
      {{ datas.planDate }}
    </el-descriptions-item>

    <el-descriptions-item v-if="datas.acceptTime">
      <template #label>
        <div class="cell-item" :style="userStore.isMobile ? mobileLabelStyle : ''">
          <el-icon :style="iconStyle">
            <Calendar />
          </el-icon>
          预计验收日期
        </div>
      </template>
      {{ datas.acceptTime }}
    </el-descriptions-item>

    <el-descriptions-item v-if="datas.completeDate">
      <template #label>
        <div class="cell-item" :style="userStore.isMobile ? mobileLabelStyle : ''">
          <el-icon :style="iconStyle">
            <Calendar />
          </el-icon>
          竣工日期
        </div>
      </template>
      {{ datas.completeDate }}
    </el-descriptions-item>

    <el-descriptions-item v-if="datas.approvalDate">
      <template #label>
        <div class="cell-item" :style="userStore.isMobile ? mobileLabelStyle : ''">
          <el-icon :style="iconStyle">
            <Calendar />
          </el-icon>
          立项日期
        </div>
      </template>
      {{ datas.approvalDate }}
    </el-descriptions-item>

    <el-descriptions-item >
      <template #label>
        <div class="cell-item" :style="userStore.isMobile ? mobileLabelStyle : ''">
          <el-icon :style="iconStyle">
            ￥
          </el-icon>
          管家婆应收金额
        </div>
      </template>
      <el-tag size="large" v-if="amountInfo.same == 2" type="primary" :style="userStore.isMobile ? 'font-size: 12px; font-weight: bold;' : 'font-size: 14px; font-weight: bold;'">{{ amountInfo.gjpShould }}</el-tag>
      <el-tag size="large" v-if="amountInfo.same == 1" type="success" :style="userStore.isMobile ? 'font-size: 12px; font-weight: bold;' : 'font-size: 14px; font-weight: bold;'">{{ amountInfo.gjpShould }}</el-tag>
    </el-descriptions-item>

    <el-descriptions-item v-if="datas.housekeeperName">
      <template #label>
        <div class="cell-item" :style="userStore.isMobile ? mobileLabelStyle : ''">
          <el-icon :style="iconStyle">
            <FolderOpened />
          </el-icon>
          管家婆项目
        </div>
      </template>
      {{ datas.housekeeperName }}
    </el-descriptions-item>

    <el-descriptions-item v-if="datas.customerAddress">
      <template #label>
        <div class="cell-item" :style="userStore.isMobile ? mobileLabelStyle : ''">
          <el-icon :style="iconStyle">
            <office-building />
          </el-icon>
          客户地址
        </div>
      </template>
      {{ datas.customerAddress }}
    </el-descriptions-item>

    <el-descriptions-item v-if="datas.joinPeople">
      <template #label>
        <div class="cell-item" :style="userStore.isMobile ? {...mobileLabelStyle, color: 'red', fontWeight: 'bold'} : {color: 'red', fontWeight: 'bold'}">
          <el-icon :style="iconStyle">
            <tickets />
          </el-icon>
          阶段确认人
        </div>
      </template>
      <span style="color: red; font-weight: bold;">{{ datas.joinPeople }}</span>
    </el-descriptions-item>

    <el-descriptions-item v-if="datas.currentPeople">
      <template #label>
        <div class="cell-item" :style="userStore.isMobile ? {...mobileLabelStyle, color: 'red', fontWeight: 'bold'} : {color: 'red', fontWeight: 'bold'}">
          <el-icon :style="iconStyle">
            <tickets />
          </el-icon>
          当前操作人
        </div>
      </template>
      <span style="color: red; font-weight: bold;">{{ datas.joinPeople }}</span>
    </el-descriptions-item>

    <el-descriptions-item v-if="datas.remark">
      <template #label>
        <div :style="userStore.isMobile ? mobileLabelStyle : ''">
          <el-icon :style="iconStyle">
            <tickets />
          </el-icon>
          备注
        </div>
      </template>
      <span>{{ datas.remark }}</span>
    </el-descriptions-item>

    <el-descriptions-item v-if="datas.phaseRemark">
      <template #label>
        <div :style="userStore.isMobile ? mobileLabelStyle : ''">
          <el-icon :style="iconStyle">
            <tickets />
          </el-icon>
          留言
        </div>
      </template>
      <span>{{ datas.phaseRemark }}</span>
    </el-descriptions-item>
</el-descriptions>



  <div v-if="personList.length > 0 && isView">
    <el-divider style="font-size: 16px; font-weight: bold;">参与人员信息</el-divider>
    <el-table :data="personList" border>
      <el-table-column label="标签页" align="center" width="180" prop="phaseName" />
      <el-table-column label="参与人" align="center" width="200" prop="participanName" />
      <el-table-column label="岗位" align="center" prop="postName" />
      <el-table-column label="开始日期" align="center" width="120" prop="startDate" />
      <el-table-column label="结束日期" align="center" prop="endDate" />
      <el-table-column label="备注" align="center" width="120" prop="remark" />
      <el-table-column label="操作员" align="center" prop="operator" />
      <el-table-column label="操作时间" align="center" prop="startDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d} {h}:{i}:{s}") }}</span>
        </template>
      </el-table-column>
    </el-table>
  </div>


  <div v-if="attachmentList.length > 0 && isView">
    <el-divider style="font-size: 16px; font-weight: bold;">附件信息</el-divider>
    <el-table :data="attachmentList" border>
      <el-table-column label="标签页" align="center" prop="phaseName" />
      <el-table-column label="附件类别" align="center" prop="attachmentType">
        <template #default="scope">
          <dict-tag :options="file_type" :value="scope.row.attachmentType" />
        </template>
      </el-table-column>
      <el-table-column label="附件标题" align="center" prop="attachmentTitle" />
      <el-table-column label="附件名称" align="center" show-overflow-tooltip width="200" prop="fileName">
        <template #default="scope">
          <el-link type="primary" @click="downloadFile(scope.row)">{{ scope.row.fileName }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="操作员" align="center" prop="operator" />
    </el-table>
  </div>

  <div v-if="payList.length > 0 && isView">
    <el-divider style="font-size: 16px; font-weight: bold;">收款信息</el-divider>
    <el-table :summary-method="getPaySummary" show-summary border :data="localPayList">
      <el-table-column label="付款公司" align="center" prop="company" />
      <el-table-column label="合同签订金额" align="center" width="120" show-overflow-tooltip prop="totalAmount" />
      <el-table-column label="结算金额" align="center" width="120" show-overflow-tooltip prop="settlementAmount" />
      <!-- <el-table-column label="付款百分比" align="center" prop="percentage" /> -->
      <!-- <el-table-column label="金额" align="center" prop="amount" /> -->
      <!-- <el-table-column label="附件" align="center" prop="files" /> -->
      <el-table-column label="备注" width="220" show-overflow-tooltip align="center" prop="remark" />
      <el-table-column label="发票编号" align="center" width="220" show-overflow-tooltip prop="payNo" />
      <el-table-column label="财务实收金额" align="center" width="120" show-overflow-tooltip prop="receivedAmount" />
      <el-table-column label="收到期票/承兑/保函" align="center" width="120" show-overflow-tooltip prop="promissoryNote" />
      <el-table-column label="期票/承兑/保函到期时间" align="center" prop="promissoryEndDate" />
      <el-table-column label="财务实收百分比(%)" align="center" prop="receivedPercentage" />
      <el-table-column label="附件" align="center" show-overflow-tooltip width="200" prop="fileName">
        <template #default="scope">
          <el-link type="primary" @click="downloadFile(scope.row)">{{ scope.row.fileName }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" :width="userStore.isMobile ? 120 : 250" class-name="small-padding fixed-width">
              <template #default="scope">
                <el-button link type="primary"   :icon="userStore.isMobile ? '':'Edit'"
                  @click="handleUpdatePay(scope.row)">完善收款信息</el-button>
              </template>
            </el-table-column>
    </el-table>
  </div>

      <!-- 添加或修改付款对话框 -->
      <el-dialog title="收款信息" v-model="openPay" :width="userStore.isMobile ? '95%' : '800px'"  append-to-body>
<el-form ref="payRef" size="large" :model="payForm" :rules="payRules"
         :label-width="userStore.isMobile ? '100px' : '120px'">

  <el-row :gutter="userStore.isMobile ? 10 : 20">
    <el-col :span="userStore.isMobile ? 24 : 15">
      <el-form-item width="200" label="付款公司" prop="company">
        <el-input v-model="payForm.company" placeholder="请输入付款公司" style="width: 100%" />
      </el-form-item>
    </el-col>
  </el-row>

  <el-row :gutter="userStore.isMobile ? 10 : 20">
    <el-col :span="userStore.isMobile ? 24 : 10">
      <el-form-item label="合同签订金额(元)" prop="totalAmount">
        <el-input type="number" @wheel.native.prevent :disabled="true"
                  v-model="payForm.totalAmount" placeholder="请输入合同签订金额"
                  style="width: 100%" />
      </el-form-item>
    </el-col>
  </el-row>

  <el-row :gutter="userStore.isMobile ? 10 : 20">
    <el-col :span="userStore.isMobile ? 24 : 10">
      <el-form-item label="合同结算金额(元)" prop="settlementAmount">
        <el-input type="number" @wheel.native.prevent :disabled="true"
                  v-model="payForm.settlementAmount" placeholder=""
                  style="width: 100%" />
      </el-form-item>
    </el-col>
  </el-row>

  <el-row :gutter="userStore.isMobile ? 10 : 20">
    <el-col :span="userStore.isMobile ? 24 : 20">
      <el-form-item label="内容" prop="remark">
        <el-input v-model="payForm.remark" :disabled="true" type="textarea" :rows="3"
                  placeholder="请输入内容" style="width: 100%" />
      </el-form-item>
    </el-col>
  </el-row>

  <!-- 财务补充收款记录 -->
  <div>
    <el-divider style="font-size: 16px; font-weight: bold;"></el-divider>

    <el-row :gutter="userStore.isMobile ? 10 : 20">
      <el-col :span="userStore.isMobile ? 24 : 20">
        <el-form-item  width="200" label="发票编号" prop="payNo">
          <el-input v-model="payForm.payNo" placeholder="" style="width: 100%" />
        </el-form-item>
      </el-col>
    </el-row>

    <el-row :gutter="userStore.isMobile ? 10 : 20">
      <el-col :span="userStore.isMobile ? 24 : 10">
        <el-form-item label="开票日期">
          <el-date-picker clearable v-model="payForm.financeDate" type="date"
                          value-format="YYYY-MM-DD" placeholder="请选择开票日期"
                          style="width: 100%" />
        </el-form-item>
      </el-col>
    </el-row>

    <el-row :gutter="userStore.isMobile ? 10 : 20">
      <el-col :span="userStore.isMobile ? 24 : 10">
        <el-form-item label="财务实收金额(元)" prop="receivedAmount">
          <el-input type="number" @wheel.native.prevent :disabled="true"
                    v-model="payForm.receivedAmount" @blur="handleBlur(2)"
                    placeholder="请输入财务实收金额" style="width: 100%" />
        </el-form-item>
      </el-col>
    </el-row>

    <el-row :gutter="userStore.isMobile ? 10 : 20">
      <el-col :span="userStore.isMobile ? 24 : 10">
        <el-form-item label="财务实收(%)" prop="receivedPercentage">
          <el-input :disabled="true" v-model="payForm.receivedPercentage"
                    placeholder="财务实收(%)" style="width: 100%" />
        </el-form-item>
      </el-col>
    </el-row>

    <el-form-item label="附件" prop="files">
      <file-upload :limit="1" v-model="payForm.files" style="width: 100%" />
    </el-form-item>
  </div>

</el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitPayForm">确 定</el-button>
          <el-button @click="cancelPay">取 消</el-button>
        </div>
      </template>
    </el-dialog>



  <div v-if="implementList.length > 0 && isView">
    <el-divider style="font-size: 16px; font-weight: bold;">实施日志信息</el-divider>
    <el-table border :data="implementList">
      <el-table-column label="实施日期" align="center" prop="implementDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.implementDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="附件照片" align="center" prop="images" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.images" v-if="scope.row.images" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="标题" align="center" prop="title" />
      <el-table-column label="内容" align="center" prop="remark" />
      <el-table-column label="文件类型" align="center" prop="fileType">
        <template #default="scope">
          <dict-tag :options="log_type" :value="scope.row.fileType" />
        </template>
      </el-table-column>

      <el-table-column label="附件" align="center" width="250">
                <template #default="scope">
                  <div v-if="hasFiles(scope.row)">
                    <div v-for="(file, index) in scope.row.files.split(',')" :key="index" style="margin-bottom: 4px;">
                      <!-- 判断是否是图片 -->
                      <template v-if="isImage(file)">
                        <image-preview :src="file" :width="50" :height="50" />
                      </template>
                      <template v-else>
                        <el-link type="primary" @click="downloadFileImp(file)">
                          {{ getFileNameImp(file) }}
                        </el-link>
                      </template>
                    </div>
                  </div>
                  <div v-else>--</div>
                </template>
              </el-table-column>

      <el-table-column label="操作人" align="center" prop="operator" />
      <el-table-column label="操作时间" align="center" prop="startDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d} {h}:{i}:{s}") }}</span>
        </template>
      </el-table-column>

    </el-table>
  </div>


  <div v-if="accountingList.length > 0 && isView && isSales">
    <el-divider style="font-size: 16px; font-weight: bold;">项目核算信息</el-divider>
    <el-table :summary-method="getSummary" show-summary border :data="accountingList">
      <el-table-column label="类型" align="center" prop="type">
        <template #default="scope">
          <dict-tag :options="profit_type" :value="scope.row.type" />
        </template>
      </el-table-column>
      <el-table-column label="此类型的结算总额" align="center" width="100" prop="projectAmount" />
      <el-table-column label="项目税额" align="center" width="100" prop="taxAmount" />
      <el-table-column label="项目材料成本" align="center" width="100" prop="materialCost" />
      <el-table-column label="其他成本一(报销费用)" align="center" width="100" prop="costOne" />
      <el-table-column label="其他成本二" align="center" width="100" prop="costTwo" />
      <el-table-column label="其他成本三" align="center" width="100" prop="costThree" />
      <el-table-column label="资金成本" align="center" width="100" prop="fundCost" />
      <el-table-column label="外协人工成本" align="center" width="100" prop="laborCost" />
      <el-table-column label="税率(%)" align="center" prop="rate" />
      <el-table-column label="毛利润" align="center" width="100" prop="profit" />
      <el-table-column label="成本税费" align="center" width="100" prop="costFees" />
      <el-table-column label="差额税费" align="center" width="100" prop="differenceFees" />
      <el-table-column label="税前利润" align="center" width="100" prop="beforeProfit" />
      <el-table-column label="质保金" align="center" width="100" prop="retentionMoney" />
      <el-table-column label="纯利润扣质保金" align="center" width="100" prop="afterProfit" />
      <el-table-column label="项目提成" align="center" width="100" prop="projectCommission" />
      <el-table-column label="操作员" align="center" prop="operator" />
    </el-table>
  </div>



  <div v-if="warrantyList.length > 0 && isView">
    <el-divider style="font-size: 16px; font-weight: bold;">项目质保信息</el-divider>
    <el-table border :data="warrantyList">
      <el-table-column label="付款单位" align="center" prop="company" />
      <el-table-column label="结算金额" align="center" prop="settlementAmount" />
      <!-- <el-table-column label="质保金比例(%)" align="center" prop="warrantyPercentage" /> -->
      <el-table-column label="质保金" align="center" prop="warranty" />
      <el-table-column label="税率(%)" align="center" prop="rate">
        <template #default="scope">
          <dict-tag :options="warranty_rate" :value="scope.row.rate" />
        </template>
      </el-table-column>
      <el-table-column label="周期(月)" align="center" prop="cycle" />
      <el-table-column label="起始日期" align="center" prop="startDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.startDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>

      <el-table-column label="截止日期" align="center" prop="endDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.endDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="质保到期剩余(天)" align="center" prop="warrantyRemaining" />

      <el-table-column label="质保金实收金额" align="center" prop="receivedAmount" />
      <el-table-column label="操作人" align="center" prop="operator" />
      <el-table-column label="文件名称" align="center" show-overflow-tooltip width="200" prop="fileName">
        <template #default="scope">
          <div v-if="scope.row.files">
            <el-link v-for="(file, index) in scope.row.fileName.split(',')" :key="index" type="primary"
              @click="downloadFileW(scope.row, index, file)" style="display: block; margin-bottom: 5px;">
              {{ file }}
            </el-link>
          </div>
          <div v-else>
            <!-- 无文件 -->
          </div>
        </template>
      </el-table-column>
    </el-table>
  </div>

  <allocation v-if="viewAllocation && userStore.name == 'wuzg'" ref="allocationRef"></allocation>

</template>


<script setup name="ProjectView">
import { onMounted, toRefs } from 'vue';
const props = defineProps({
  datas: {
    type: Object, // 指定类型为对象
    required: true, // 是否必填
  },
  column: {
    type: Number, // 指定类型为数字
    default: 3, // 设置默认值为 3
  },
  sizes: {
    default: 'default',
  },
  personList: {
    default: [],
  },
  payList: {
    default: [],
  },
  attachmentList: {
    default: [],
  },
  implementList: {
    default: [],
  },
  warrantyList: {
    default: [],
  },
  accountingList: {
    default: [],
  },


  isView: {
    default: false,
  },


});
import {
  getStepList, getAmountInfo, getPermission,getPay,updatePay,listPay
} from "@/api/project/project";
import { ref } from 'vue';
import useUserStore from '@/store/modules/user'

const userStore = useUserStore()
const { datas, column, sizes, personList, payList, attachmentList, implementList, accountingList, warrantyList, isView } = toRefs(props);
const iconStyle = computed(() => {
  const marginMap = {
    large: '8px',
    default: '6px',
    small: '4px',
  }
  return {
    marginRight: marginMap[sizes.value] || marginMap.default,
  }
})

//显示竣工日期
const compeleteDate = ref('')


const { proxy } = getCurrentInstance();
const { project_type } = proxy.useDict("project_type");
const { phase_type } = proxy.useDict("phase_type");
const { file_type } = proxy.useDict('file_type');
const { log_type } = proxy.useDict('log_type');
const { profit_type } = proxy.useDict('profit_type');
const { warranty_rate } = proxy.useDict('warranty_rate');

const projectList = ref([]);
const companyList = ref([]);
const open = ref(false);
const openPhase = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeAcceptTime = ref([]);
const phasetList = ref([]);
const completeObj = ref();
const openPay = ref(false);
let currentPhase = reactive({
  phaseCode: '',
});
const logs = ref([]);
const data = reactive({
  form: {
    createUserName: null,
    createUserId: null,
    createDeptName: null,
    createDept: null,
  },
  amountInfo: {
    should: null,
    actual: null,
    remaining: null,
    gjpShould: null,
    same:null
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    projectName: null,
    projectAmount: null,
    projectType: null,
    projectUnit: null,
    acceptTime: null,
    customerName: null,
    housekeeperProject: [],
    phaseCode: null,
  },
  rules: {},
  payForm: {

},
payRules: {
    company: [{ required: true, message: "请输入付款公司", trigger: "blur" }],
  }


});
const { payForm,payRules } = toRefs(data);

// 判断是否有文件
function hasFiles(row) {
  return row.files && typeof row.files === 'string' && row.files.trim() !== '';
}

// 提取文件名
function getFileNameImp(filePath) {
  if (!filePath) return '';

  // 1. 提取文件名部分（带扩展名）
  const fileNameWithExt = filePath.split('/').pop();

  // 2. 分离文件名和扩展名
  const lastDotIndex = fileNameWithExt.lastIndexOf('.');
  if (lastDotIndex === -1) return fileNameWithExt;

  const ext = fileNameWithExt.slice(lastDotIndex); // .docx / .png 等
  let baseName = fileNameWithExt.slice(0, lastDotIndex); // 去掉扩展名的部分

  // 3. 取第一个 '_' 前面的内容
  const firstUnderscoreIndex = baseName.indexOf('_');
  if (firstUnderscoreIndex > 0) {
    baseName = baseName.substring(0, firstUnderscoreIndex);
  }
  // 如果没有 '_'，则保持原样

  // 4. 返回美化后的文件名
  return baseName + ext;
}
function isImage(file) {
  return /\.(png|jpe?g|gif|bmp|webp)$/i.test(file);
}
// 表单重置
function resetPay() {
  payForm.value = {
  };
  proxy.resetForm("payRef");

}
// 取消按钮
function cancelPay() {
  openPay.value = false;
  resetPay();
}

const payProjectNo = ref('')

function handleUpdatePay(row) {
  console.log("rrrrr",row)
  payProjectNo.value = row.projectNo
  resetPay();
  const _Id = row.id || ids.value
  getPay(_Id).then(response => {
    payForm.value = response.data;
    openPay.value = true;
  });
}

// 获取文件名称
function getFileName(name) {
  if (name) {
    // 如果是url那么取最后的名字 如果不是直接返回
    if (name.lastIndexOf("/") > -1) {
      return name.slice(name.lastIndexOf("/") + 1);
    } else {
      return name;
    }
  }
}

// 定义本地响应式变量
const localPayList = ref([]);

// 监听 props.payList 变化并初始化
watchEffect(() => {
  localPayList.value = [...(payList.value || [])]; // 深拷贝或浅拷贝看需要
});



/** 提交按钮 */
function submitPayForm() {
  proxy.$refs["payRef"].validate(valid => {
    if (valid) {
      payForm.value.projectNo = payProjectNo.value
      payForm.value.fileName = getFileName(payForm.value.files)
      if (payForm.value.id != null) {
        // handleBlur(2)
        updatePay(payForm.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          openPay.value = false;

        }).then(() => {
          let params = {
            projectNo: payProjectNo.value
          }
        // 在请求后更新本地变量
        listPay(params).then((response) => {
          localPayList.value = response.data;
        });
        })
      } else {
        addPay(payForm.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          openPay.value = false;
        });
      }
    }
  });
}


async function downloadFile(row) {
  //只有项目经理 销售负责人 吴总 能够下载正式清单 竣工结算清单 正式合同
  if (row.attachmentType == '4' || row.attachmentType == '5' || row.attachmentType == '22') {
    let params = {
      projectNo: row.projectNo,
      postIds: [2, 5,6,7]//传入岗位id  项目经理id 2  销售负责人 5  销售 9 商务 7 财务 6
    }
    const res = await getPermission(params).then((response) => {
      console.log("下载附件", response.data);
      return response.data
    });
    if (!res) {
      proxy.$modal.msgError("暂无权限下载此附件");
      return
    }
  }

  var name = row.fileName;
  var url = row.filePath || row.files;
  // var suffix = url.substring(url.lastIndexOf("."), url.length);
  const a = document.createElement('a')
  a.setAttribute('download', name)
  a.setAttribute('target', '_blank')
  a.setAttribute('href', import.meta.env.VITE_APP_BASE_API + url)
  a.click()
}
function getSummary(param) {
  const { columns, data } = param;

  const sums = [];

  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计';
      return;
    }

    const key = column.property;
    const validKeys = [
      'projectAmount',
      'taxAmount',
      'materialCost',
      'costOne',
      'costTwo',
      'costThree',
      'fundCost',
      'laborCost',
      'profit',
      'costFees',
      'differenceFees',
      'beforeProfit',
      'retentionMoney',
      'afterProfit',
      'projectCommission'
    ];

    if (!validKeys.includes(key)) {
      sums[index] = '';
      return;
    }

    const sum = data.reduce((acc, item) => {
      return acc + (Number(item[key]) || 0);
    }, 0);

    sums[index] = sum.toFixed(2);
  });

  return sums;
}


function getPaySummary(param) {
  const { columns, data } = param;

  const sums = [];

  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计';
      return;
    }

    const key = column.property;
    const validKeys = [
      'receivedAmount',
      'receivedPercentage',
      'promissoryNote'
    ];

    if (!validKeys.includes(key)) {
      sums[index] = '';
      return;
    }

    const sum = data.reduce((acc, item) => {
      return acc + (Number(item[key]) || 0);
    }, 0);

    sums[index] = sum.toFixed(2);
  });

  return sums;
}

const mobileLabelStyle = {
  fontWeight: 'bold',
  padding: '8px 0',
  fontSize: '14px'
}

function downloadFileW(row, index, name) {
  // var name = row.fileName;
  // var url = row.filePath || row.files;
  // var suffix = url.substring(url.lastIndexOf("."), url.length);
  let fileArr = row.files.split(',')
  const a = document.createElement('a')
  a.setAttribute('download', name)
  a.setAttribute('target', '_blank')
  a.setAttribute('href', import.meta.env.VITE_APP_BASE_API + fileArr[index])
  a.click()
}

const { queryParams, form, rules, amountInfo } = toRefs(data);


// 动态获取每个步骤的状态
function getStatus(complete, index) {
  if (complete === 2) {
    return "success"; // 已完成的步骤
  } else if (index === activeIndex.value) {
    return "process"; // 当前进行中的步骤
  } else {
    return "wait"; // 等待中的步骤
  }
}


function initLogStatus() {
  let params = {
    projectNo: datas.value.projectNo
  }
  console.log("项目id", datas.value.projectNo);

  if (datas.value?.projectNo) {

    console.log("wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww");

    getAmountInfo(datas.value.projectNo).then((response) => {
      // getAmountInfo.value = response.data;
      console.log("金额信息", response);

      nextTick(() => {
        amountInfo.value.should = response.data.should
        amountInfo.value.actual = response.data.actual
        amountInfo.value.remaining = response.data.remaining
        amountInfo.value.gjpShould = response.data.gjpShould
        amountInfo.value.same = response.data.same
      });

    });

    getStepList(params).then((response) => {
    logs.value = response.data.list;
    completeObj.value = response.data.completeObj
    console.log("时间线", response.data);
  });

  }


}
const isSales = ref(false)


async function isSale() {
  let params = {
    projectNo: datas.value.projectNo,
    postIds: [5]//传入岗位id  项目经理id 2  销售负责人 5  销售 9 商务 7 财务 6
  }
  const res = await getPermission(params).then((response) => {
    console.log("权限信息", response.data);
    return response.data
  });
  isSales.value = res
}
const allocationRef = ref()
const openAllocation = ref(false)
import allocation from "./allocation.vue";
const viewAllocation = ref(false)


onMounted(async () => {

  isSale()
  initLogStatus()


  console.log("datassss",datas.value);
  
  // if (datas.value.phaseId >= 6 && userStore.name == 'wuzg') {
  //   viewAllocation.value = true; // 触发渲染
  //   await nextTick(); // 等待 DOM 更新
  //   if (allocationRef.value) {
  //     allocationRef.value.initData(datas.value, "2", 'accountingComplete');
  //   }
  // }
});


</script>

<style scoped></style>